// pages/xbmeet/xbmeet.js

const comm = require('../../utils/comm.js')
const todayIndex = new Date().getDate() - 1;
const con_month = new Date().getMonth() + 1
const app = getApp()

Page({

  data: {
    buttonStyle: 'button-enable',
    hasEmptyGrid: false,
    cur_year: '',
    cur_month: '',
    cur_user: '',
    cur_css: 'datesView',
    cur_index: new Date().getDate() - 1,
    date: '',
    departs:[],
    areas:[],
    room:[],
    dayStyle: [],
    styles: [],
    starttimes: [],
    endtimes: [9, 10],
    meets: [],
    haves:[],
    st: 8,
    et: 9,
    index:0,
    indx:0,
    iarea:0,
    ih: 0,
    im: 0,
    iv: 0,
    exists: false
  },
  departSelected:function(e){
    this.setData({
      indx: e.detail.value
    })
  },
  //区域选择确认后，显示对应的会议室信息
  areaPickerSelected:function(e){
    var that = this
    that.setData({
      iarea: e.detail.value
    })
    that.onInitRoom(that.data.areas[that.data.iarea])
  },
  //初始化会议室信息
  onInitRoom(area){
    var that = this
    that.setData({
      room: []
    })
    wx.request({
      url: app.globalData.serverUrl + '/room/?area='+area,
      success(res){
        for(var i=0;i< res.data.length;i++)
        {
          that.setData({
            room: that.data.room.concat(res.data[i].meet)
          })
        }
        //console.log('onInitRoom...', that.data.room)
        let v_room = that.data.room[that.data.index]
        //选择不同的会议地，日期背景色的变化；
        //console.log('onInitRoom...', v_area, that.data.room)
        that.onInit(area, v_room, that.data.cur_year, that.data.cur_month)
      },
      fail(err){
      }
    })
  },

  //会议室选择事件;
  roomPickerSelected:function(e){
    var that = this
    var v_index = e.detail.value
    that.setData({
      index: e.detail.value
    })
    var v_area = that.data.areas[that.data.iarea]
    var v_room = that.data.room[v_index]
    that.onInit(v_area, v_room,that.data.cur_year,that.data.cur_month)
  },

//初始化会议地;
  onInitDomain(){
    var that = this
    wx.request({
      url: app.globalData.serverUrl + '/domain/',
      success(res) {
        for (var i = 0; i < res.data.length; i++)
          that.setData({
            areas: that.data.areas.concat(res.data[i].area)
          })
      },
      fail(err) {
        console.log('onInitDomain Error:',err)
      }
    })
  },

  onInitDepart(){
    var that = this
    wx.request({
      url: app.globalData.serverUrl + '/depart/',
      success(res) {
        for(var i=0;i< res.data.length;i++)
        that.setData({
          departs: that.data.departs.concat(res.data[i].depart)
        })
      },
      fail(err) {
        console.log('onInitDepart Error:',err)
      }
    })
  },

 //初始化起止时间
  onInitTime(){
    var that = this
    for (let i = this.data.st; i <= 20; i++) {
      that.setData({
        starttimes: that.data.starttimes.concat(i)
      })
    }
  },
  /**
* 监听时间picker选择器
*/
  startTimePickerSelected: function (e) {
    //调用setData()重新绘制 
    this.setData({
      ih: e.detail.value
    });
    this.setData({
      et: this.data.starttimes[this.data.ih] + 1
    })
    this.data.endtimes.length = 0
    for (let j = this.data.et; j <= 24; j++) {
      this.setData({
        endtimes: this.data.endtimes.concat(j)
      })
    }
  },
  endTimePickerSelected: function (e) {
    this.setData({
      im: e.detail.value
    })
  },
  //判断是否已预订
  isHas(v_month,v_day,v_room){
    var that = this
    var isa = false
    //初始化haves内容，避免内容重复出现
    that.setData({
      haves: []
    })
    if(that.data.meets.length >0)
    {
      for(var i=0;i< that.data.meets.length;i++)
      {
        let s_month = that.data.meets[i]['month']
        let s_day = that.data.meets[i]['day']-1
        let flag = that.data.meets[i]['flag']
        let s_room = that.data.meets[i]['meet']
        if ((v_month == s_month) && (v_day == s_day) && (v_room == s_room)&&(flag =='全天'))
          {  
             isa = true
             that.setData({
               haves: []
             })
          }
          else if ((v_month == s_month) && (v_day == s_day)&&(v_room==s_room) && (flag != '全天'))
          { //获取非全天预订信息；
            let text = '*** '+that.data.meets[i]['depart'] + ": " + that.data.meets[i]['time'] + " 已预订 ***"
            that.setData({
              haves: that.data.haves.concat(text)
            })
          }
      }
    }
    return isa
  },
  //判断是上午，下午，全天
  gettime(datetime) {
    let vars = []
    let result = '';
    vars = datetime.split('-');
    let n1 = parseInt(vars[0]);
    let n2 = parseInt(vars[1]);
    if (n1 < 13 && n2 <= 13) {
      result = '上午';
      this.setData({
        cur_css: 'swdayView'
      })
    } else if (n1 >= 13 && (n2 >= 13 && n2 <= 19)) {
      result = '下午'
      this.setData({
        cur_css: 'xwdayView'
      })
    }
    else if (n1 < 11 && n2 > 13) {
      result = '全天'
      this.setData({
        cur_css: 'onedayView'
      })
    }
    return result
  },
  has_existsdata2(depart, date, room) {
    var that = this
    try {
      console.log('has_existsdata2',depart,date,room)
      wx.request({
        url: app.globalData.serverUrl + '/get-abc/?depart=' + depart + "&date=" + date + '&room=' + room,
        success(res) {
          if (res.data.length > 0) {
            that.setData({
              exists: true
            })
          }
        }
      })
    }
    catch{
    }
  },
  //数据提交
  onSave:function(e){
    var self = this
    if(self.data.date.length == 0)
    {
      wx.showModal({
        title: '提示',
        content: '请选择会议日期',
        image: '../../images/err.png'
      })
      return 
    }
    if (self.data.room.length == 0) {
      wx.showModal({
        title: '提示',
        content: '预订会议不能为空',
        image: '../../images/err.png'
      })
      return
    }

    if (typeof (self.data.cur_user) == 'undefined')
    {
      wx.showModal({
        title: '提示',
        content: '请先登录系统',
        image: '../../images/err.png'
      })
      return 
    }
    if (self.data.cur_user.length == 0)
    {
      wx.showModal({
        title: '提示',
        content: '请先登录系统',
        image: '../../images/err.png'
      })
      return 
    }
    // let v_depart = self.data.departs[self.data.indx]
    // let v_room = self.data.room[self.data.index]
    // comm.has_existsdata(v_depart, self.data.date, v_room).then(res=>{
    //   if (res) {
    //     wx.showModal({
    //       title: '提示',
    //       content: '提交信息已存在',
    //       image: '../../images/err.png'
    //     })
    //     return
    //   }
    // });
   
    let vTime = self.data.starttimes[self.data.ih] + ":00-" + self.data.endtimes[self.data.im] + ":00"
    let vflag = self.gettime(vTime);
    wx.request({
      url: app.globalData.serverUrl + '/save-data/',
      method: 'POST',
      data: {
        open_id: app.globalData.projectid,
        date: self.data.date,
        date2: self.data.cur_month + '月' + (self.data.cur_index+1)+'日',
        depart: self.data.departs[self.data.indx],
        flag: vflag,
        area: self.data.areas[self.data.iarea],
        meet: self.data.room[self.data.index],
        month: self.data.cur_month,
        year: self.data.cur_year,
        day: self.data.cur_index+1,
        time: vTime,
        user: self.data.cur_user,
        style: self.data.cur_css
      },
      header: {
        'Content-Type': 'application/json' // 默认值
      },
      success(res) {
        let status =res.statusCode;
        let result = res.data.message
        let code = res.data.code
        if(status == 200&& code==100)
        {
          //重置背景色;
          self.setDayStyle(res.data.list)
          wx.showToast({
            title: result,
          })
          self.setData({
            date: ''
          })
        }
        else
        {
           wx.showModal({
             title: '提示',
             content: result,
           })
        }
      
      },
      fail(err) {
        console.log(err)
      }
    })
  },
  //预订提交后，重置日期背景色;
  setDayStyle(list){
    var that = this
    this.setData({
      meets:[]
    })
    if(that.data.styles.length > 0 && list.length > 0)
    {
      for (var j = 0; j < list.length; j++) {
        that.setData({
          meets: that.data.meets.concat(list[j])
        })
        for (var i = 0; i <= that.data.styles.length; i++) {
          if (i == list[j].day) {
            that.data.styles[i - 1]['style'] = list[j].style
          }
        }
      }
      //需要重新赋值一次，界面才能显示
      that.setData({
        styles: that.data.styles
      })
    }
  },
  //根据年份+月份+会议地+会议室初始化日期背景色
  onInit(v_area,v_room,v_year,v_month){
    var that = this
    //初始化数据，以免出现重复记录
    that.setData({
      meets: []
    })
    if(v_area == "")
    {
      v_area = that.data.areas[0]
    }
    if(v_room == "")
    {
      v_room = that.data.room[0]
    }
    if (v_year == 0) {
      v_year = that.data.cur_year
    }
    if (v_month == 0) {
      v_month = that.data.cur_month
    }
     wx.request({
       url: app.globalData.serverUrl + '/get-abc/',
       data:{
         "year": v_year,
         "area": v_area,
         "room": v_room,
         "month": v_month
       },
       method: 'POST',
       success(res){
         //console.log(res.data)
         that.data.styles.length = 0
         //循环调用了。。。。。
         that.initdayStyles(v_month, todayIndex, 'datesView');
         if (res.data.length > 0) {
           for (var j = 0; j < res.data.length; j++) {
             that.setData({
               meets: that.data.meets.concat(res.data[j])
             })
             for (var i = 0; i <= that.data.styles.length; i++) {
               //初始化日期样式
               //that.initdayStyles(res.data[i].month, res.data[i].day, res.data[i].style);
               if (i == res.data[j].day) {
                 that.data.styles[i - 1]['style'] = res.data[j].style
               }
             }
           }
           //需要重新赋值一次，界面才能显示
           that.setData({
             styles: that.data.styles
           })
         }
       },
       fail(err){
         console.log('onInit Error:',err)
       }
     })
  },
  //第一次加载获取后台数据，重置背景色;
  onInitData(v_year,v_month){
    if(v_year == 0)
    {
       v_year = that.data.cur_year
    }
    if(v_month == 0)
    {
       v_month = that.data.cur_month
    }
    var that = this
    wx.request({
      url: app.globalData.serverUrl + '/get-data/?year='+v_year+'&month='+v_month,
      success(res){
        that.data.styles.length = 0
        //循环调用了。。。。。
        that.initdayStyles(v_month, todayIndex, 'datesView');       
        if(res.data.length > 0)
        {
          for (var j = 0; j < res.data.length; j++)
          {
            that.setData({
              meets: that.data.meets.concat(res.data[j])
            })
            for (var i = 0; i <= that.data.styles.length; i++ ) {
              //初始化日期样式
              //that.initdayStyles(res.data[i].month, res.data[i].day, res.data[i].style);
              if(i == res.data[j].day)
              {
                that.data.styles[i-1]['style'] = res.data[j].style
              }
            }
          }
          //需要重新赋值一次，界面才能显示
          that.setData({
            styles: that.data.styles
          })
        }
      },
      fail(err){
        console.log(err)
      }
    })
  },

  onLoad(options) {
    //console.log('onload....')
    this.onInitTime();
    this.onInitDomain();
    this.onInitDepart();
    this.onInitRoom('六里桥4楼')
    this.setNowDate();
    //this.onInitData(this.data.cur_year,this.data.cur_month);
    //this.onInit(this.data.areas[0],this.data.room[0],this.data.cur_year,this.data.cur_month)
  },
  //缓存中获取部门和预认人信息；
  onlogin_init(){
    var that = this;
    var array = that.data.departs;
    var res = wx.getStorageSync('userinfo');
    if (res != null) {
      let temp_deparpt = res.depart;
      that.setData({
        cur_user: res.username
      })
      for (var i = 0; i < array.length; i++) {
        //获取预订人所在部门
        if (temp_deparpt == array[i]) {
          that.setData({
            indx: i
          })
        }
      }
    }
  },
  onShow: function () {
    //console.log('onshow....')
  },
  /**
 * 生命周期函数--监听页面初次渲染完成
 */
  onReady: function () {
    //console.log('onReady....')
    this.onInit(this.data.areas[0], this.data.room[0], this.data.cur_year, this.data.cur_month)
    this.onlogin_init()
  },

  //'datesView', 'onedayView', 'swdayView','xwdayView',''
  //日期点击事件
  dateSelectAction: function (e) {
    var cur_day = e.currentTarget.dataset.idx;
    this.setData({
      cur_index: cur_day
    })
    //console.log(`点击的日期:${this.data.cur_year}年${this.data.cur_month}月${cur_day + 1}日`);
    if (this.data.cur_month >= con_month) {
      if (this.data.cur_month == con_month) {
        if (this.data.todayIndex > cur_day) {
          this.setData({
            date: '',
            haves: []
          })
          wx.showModal({
            title: '提示',
            content: '日期不能小于当前日期',
          });
          return
        }
      }
    }
    else {
      this.setData({
        date: '',
        haves: []
      })
      wx.showModal({
        title: '提示',
        content: '请选择当月或之后的日期',
        image: '../../images/err.png'
      })
      return
    }
    let v_room = this.data.room[this.data.index]
    //判断已预订日期
    if(this.isHas(this.data.cur_month,cur_day,v_room))
    {
       wx.showModal({
         title: '提示',
         content: `${cur_day+1}已预订`,
       })
       return 
    }
    this.setData({
      date: `${this.data.cur_year}-${this.data.cur_month}-${cur_day + 1}`
    })
  },

  initdayStyles(month,day,css) {
    var that = this;
    let datas ={}
    //console.log('month='+month+",day="+day+",css="+css)
    for (var i = 0; i < 31; i++) {
      if(i == todayIndex)
      {
        datas = {
          month: month,
          day: i,
          style: 'currDateView'
        }
      }
      else if(i == day)
      {
        datas={
          month:month,
          day:i,
          style:css
        }
      }
      else {
        datas = {
          month: month,
          day: i,
          style: 'datesView'
        } 
      }
      this.setData({
        styles: this.data.styles.concat(datas)
      })
    }
  },

  //初始化样式表;
  initStyle() {
    //初始化样式
    for (var i = 0; i <= 31; i++) {
      if (i == todayIndex) {
        this.setData({
          dayStyle: this.data.dayStyle.concat('currDateView')
        })
      }
      else if (i == 2) {
        this.setData({
          dayStyle: this.data.dayStyle.concat('onedayView')
        })
      }
      else if (i == 23) {
        this.setData({
          dayStyle: this.data.dayStyle.concat('swdayView')
        })
      }
      else {
        this.setData({
          dayStyle: this.data.dayStyle.concat('datesView')
        })
      }
    }
  },

  setNowDate: function () {
    const date = new Date();
    const cur_year = date.getFullYear();
    const cur_month = date.getMonth() + 1;
    const todayIndex = date.getDate() - 1;
    //console.log(`日期：${todayIndex}`)
    const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
    this.calculateEmptyGrids(cur_year, cur_month);
    this.calculateDays(cur_year, cur_month);
    this.setData({
      cur_year: cur_year,
      cur_month: cur_month,
      weeks_ch,
      todayIndex,
    })
    //初始化日期样式
    this.initdayStyles(cur_month, todayIndex,'datesView');
  },

  //按年+月获取月的天数;
  getThisMonthDays(year, month) {
    return new Date(year, month, 0).getDate();
  },

  getFirstDayOfWeek(year, month) {
    return new Date(Date.UTC(year, month - 1, 1)).getDay();
  },

  calculateEmptyGrids(year, month) {
    const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
    let empytGrids = [];
    if (firstDayOfWeek > 0) {
      for (let i = 0; i < firstDayOfWeek; i++) {
        empytGrids.push(i);
      }
      this.setData({
        hasEmptyGrid: true,
        empytGrids
      });
    } else {
      this.setData({
        hasEmptyGrid: false,
        empytGrids: []
      });
    }
  },  // end calculateEmptyGrids

  calculateDays(year, month) {
    let days = [];
    const thisMonthDays = this.getThisMonthDays(year, month);
    for (let i = 1; i <= thisMonthDays; i++) {
      days.push(i)
    }
    this.setData({
      days
    });
  },  // end calculateDays(year, month)

  //上月、下月按钮事件
  handleCalendar(e) {
    const handle = e.currentTarget.dataset.handle;
    const cur_year = this.data.cur_year;
    const cur_month = this.data.cur_month;
    let newYear = cur_year
    let newMonth = cur_month
    if (handle === 'prev') {
      newMonth = cur_month - 1;
      newYear = cur_year;
      if (newMonth < 1) {
        newYear = cur_year - 1;
        newMonth = 12;
      }

      this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);

      this.setData({
        cur_year: newYear,
        cur_month: newMonth
      })

    } else {
      newMonth = cur_month + 1;
      newYear = cur_year;
      if (newMonth > 12) {
        newYear = cur_year + 1;
        newMonth = 1;
      }

      this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);

      this.setData({
        cur_year: newYear,
        cur_month: newMonth
      })
    }
    //以下为避免meets有重复的内容，使得haves重复显示
    this.setData({
      meets:[]
    })
    //年份+月份变更时
    //this.onInitData(newYear, newMonth)
    this.onInit(this.data.areas[this.data.iarea],this.data.room[this.data.index],newYear,newMonth)
    this.setData({
      haves: [],
      date: ''
    })
  }  // end handleCalendar(e)
})
